#include <iostream>
#include <pthread.h> //原生线程库头文件
#include <unistd.h>

std::string ToHex(pthread_t tid)
{
    char id[64];
    snprintf(id, sizeof(id), "0x%ld", tid);
    return id;
}

//同一个进程内的线程，大部分资源是被共享的，因为地址空间时共享的
int g_val = 100;


//线程退出
//1.代码跑完，结果对
//2.代码跑完，结果不对
//3.异常——多线程中，任何一个线程出异常，都会导致整个进程退出
void *threadrun(void *args)
{
    int cnt = 5;
    std::string threadname = (char *)args;
    while (cnt)
    {
        printf("main thread g_val=%d, &g_val=%p\n", g_val, &g_val);
        g_val++;
        // std::cout << threadname << " thread is runing: " << ", pid:"
        //           << getpid() << " mythread id:" << ToHex(pthread_self()) << std::endl;
        sleep(1);

        //故意野指针——测试异常
        int* p = nullptr;
        *p = 10;
        cnt--;
    }
    return (void *)123;
}
int main()
{
    // 1.id
    pthread_t tid;
    pthread_create(&tid, nullptr, threadrun, (void *)"thread-1");

    // 2.新和主线程谁先运行呢？不确定，由调度器决定
    int cnt = 10;
    while (true)
    {
        printf("main thread g_val=%d, &g_val=%p\n", g_val, &g_val);
        // std::cout << "main thread is runing: " << ", pid:"
        //           << getpid() << " new thread id:" << ToHex(tid)
        //           << " main thread id:" << ToHex(pthread_self()) << std::endl;
        sleep(1);
        cnt--;
    }

    //不考虑线程异常——一旦出异常，进程直接退出，根本就到不了这里
    void *ret = nullptr; // 64位下指针的大小时8个字节
    //线程等待  
    int n = pthread_join(tid, &ret);//这里怎么没有像进程一样获取线程退出时候的信号？而是要手动写退出码
    std::cout << "main thread quit, n = " << n << " main thread get a ret:" << (long long)ret << std::endl;
    sleep(5);
    return 0;
}
